//
//  WBAnimationViewController.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/21.
//  Copyright © 2016年 木木. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

let high = USC_hight / 3
let itemMargin:CGFloat = 4
let itemW = (USC_width - CGFloat(4)*itemMargin) / CGFloat(3)

class WBAnimationViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        self.view.backgroundColor = UIColor.cyan
    }
    
    //MARK:  -
    //MARK:  - 为监听键盘  注册通知
    
    func registerNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    func keyboardChanged(n:Notification){
        
        let endFrame = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        //修改约束
        let offSetY = -(USC_hight - endFrame.origin.y)
        //更新约束
        UIView.animate(withDuration: 0.25) {
            self.tooBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offSetY)
            })
            //强制属性页面
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    //MARK:
    // MARK: - 图片的collectionView 控制器
    lazy var photoVC:WBPhotoViewController = {
        let flowLayout = UICollectionViewFlowLayout()
        let Pvc = WBPhotoViewController(collectionViewLayout: flowLayout)
        Pvc.collectionView?.backgroundColor = UIColor.cyan
        flowLayout.itemSize = CGSize(width: itemW, height: itemW)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.sectionInset = UIEdgeInsets(top: itemMargin, left: itemMargin, bottom: 0, right: 0)
        
        return Pvc
    }()
    
    func addPhotoVC(){
        self.addChildViewController(photoVC)
        self.view.addSubview(photoVC.view)
        didMove(toParentViewController: self)
        
        photoVC.view.snp.makeConstraints { (make) in
            make.trailing.leading.bottom.equalTo(self.view)
            make.top.equalTo(textView.snp.bottom)
        }
        
        
    }

    
    func setupUI(){
        
        //添加键盘通知
        registerNotification()
        
        let lblText  = UILabel()
        lblText.numberOfLines = 2
        lblText.textAlignment = .center
        
        if let userName = WBUserAccessViewModel.shared.userAccount?.name {
            let titleText = "发布微博\n\(userName)"
            lblText.text = titleText
            //修改文本属性
            let strM = NSMutableAttributedString(string: titleText)
            //获取用户名的范围
            let range = (titleText as NSString).range(of: userName)
            //给用户名添加属性
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: range)
            //给lable的属性文本赋值
            lblText.attributedText = strM
            
            
        }else{
            lblText.text = "发布微博"
        }
        lblText.sizeToFit()
        self.navigationItem.titleView = lblText
        
        addText()
        
        addPhotoVC()
        
        setToobBar()
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imgName: " ", font: 14, target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = sendBtn
    }
    
    func close(){
        self.dismiss(animated: true, completion: {
        })
    }
    func sendMessage(){
         var urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = ["access_token": WBUserAccessViewModel.shared.userAccount?.access_token,
                          "status":textView.text]
        
        //判断 是图片上传 还是文字上传
        if photoVC.imageARR.count == 0 {
            
            HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters, finished: {(reqponsObject,error) in
                if error != nil{
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showError(withStatus: "发送成功!")
                self.navigationController?.dismiss(animated: true, completion: {
                    
                })
            })
            
        }else{
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //图片
            let imageData = UIImagePNGRepresentation(self.photoVC.imageARR.first!)
            
            HMNetworkTools.shared.post(urlString, parameters: parameters, constructingBodyWith: { (fromdata) in
              /*
                 将需要上传的文件的二进制数据凭借到formadata中
                 withFileData:需要上传的文件的二进制数据
                 name:服务器接受的字段"pic"
                 fileName:服务器存储名称,新浪微博服务器会对用户上传的图片按照自己的规则进行处理
                 mineType:标识文件类型
                 */
                
            fromdata.appendPart(withFileData: imageData!, name: "pic", fileName: "suibian", mimeType: "application/octet-stream")
                
            }, progress: { (_) in
            }, success: { (_, responseObject) in
                SVProgressHUD.showError(withStatus: "发布微博成功!")
                self.navigationController?.dismiss(animated: true, completion: {
                    
                })

            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发布微博失败!请重新发布")
            })
            
        }
        
        
    }
    
    func  addText(){
        
        self.view.addSubview(textView)
        textView.addSubview(lblSpaceText)
        
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view)
            make.leading.trailing.equalTo(self.view)
            make.height.equalTo(high)
        }
        
        lblSpaceText.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(3)
            make.leading.equalTo(textView).offset(0)
            
        }
    }
    
    
    //MARK:  -
    //MARK:  - 创建一个textView
  lazy var textView : UITextView = {
    let tv = UITextView()
    tv.font = UIFont.systemFont(ofSize: 18)
    tv.textColor = UIColor.darkGray
    //添加占位文字
     tv.delegate = self
    
    tv.keyboardDismissMode = .onDrag
    tv.alwaysBounceVertical = true
    
    tv.backgroundColor = #colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)
    
    return tv
    }()
    
    ///MARK:
    // MARK: - 移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    lazy var lblSpaceText = UILabel(title: "请输入", titleColor: UIColor.gray, font: UIFont.systemFont(ofSize: 18))

    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
    
    
    //加载底部工具条
    
    lazy var tooBar:UIStackView = {
        
        let bottomBar  = UIStackView(frame: CGRect.zero)
        //设置方向
        bottomBar.axis = .horizontal
        //设置填充的方式
        bottomBar.distribution = .fillEqually
        return bottomBar
    }()
    
    func setToobBar(){
        self.view.addSubview(tooBar)
        
        tooBar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(50)
        }
        tooBar.layoutIfNeeded()
        
        tooBar.backgroundColor = UIColor.red
        
        //添加按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        
        for (index,imageName) in imageNames.enumerated() {
            let btn = UIButton()
            
            btn.setImage(UIImage(named:imageName), for: .normal)
            btn.backgroundColor = UIColor(white: 0.9, alpha: 1)
            
            btn.sizeToFit()
            tooBar.addArrangedSubview(btn)
            
            btn.addTarget(self, action: #selector(clickJump(btn:)), for: .touchUpInside)
            btn.tag = index + 100
            
            
        }
        
        
    }
    
    func clickJump(btn:UIButton){
        print("跳")
        print("\(btn.tag)")
    }
    
    
  
    
}

extension WBAnimationViewController:UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        sendBtn.isEnabled = textView.hasText
        
        lblSpaceText.isHidden = textView.hasText
    }
    
    
}









